package com.xhga.client;

import com.xhga.common.RpcRequest;
import com.xhga.register.RpcDiscover;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;

/**
 * Created by Hua wb on 2018/11/29.
 */
public class RpcProxy {
    @SuppressWarnings("all")
    public <T> T getInstance(Class<T> cls) {
        T instance  = (T)Proxy.newProxyInstance(cls.getClassLoader(), new Class[]{cls},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        //创建请求对象
                        RpcRequest rpcRequest = new RpcRequest();
                        String className = method.getDeclaringClass().getName();
                        Class<?>[] parameterTypes = method.getParameterTypes();
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        rpcRequest.setClassName(className);//类名
                        rpcRequest.setParameterTypes(parameterTypes);//参数类型列表
                        rpcRequest.setParameters(args);//参数列表
                        rpcRequest.setMethodName(method.getName());//调用的放方法名称
                        RpcClient rpcClient = new RpcClient(rpcRequest);
                        return rpcClient.send().getResult();
                    }
                }
        );
        return instance;
    }
}
